var layer = layui.layer;

if (!window.console || !window.console.log) {
    window.console = {
        log: function (msg) {
            return;
        }
    };
}

var FileUtils = {
    formatSize: function (bytes) {//格式化输出文件大小
        if (bytes === 0)
            return '0 B';

        var k = 1024,
            sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
            i = Math.floor(Math.log(bytes) / Math.log(k));
        return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
    }
};

//判断是否是IE浏览器
function isIE() {
    if (!!window.ActiveXObject || "ActiveXObject" in window) {
        return true;
    }
    return false;
}

//防止事件冒泡
function stopPropagation(e) {
    if (e.stopPropagation) {
        e.stopPropagation();
    } else {
        e.cancelBubble = true;
    }
}

/*两种调用方式
var template1="我是{0}，今年{1}了";
var template2="我是{name}，今年{age}了";
var result1=template1.format("loogn",22);
var result2=template2.format({name:"loogn",age:22});
//两个结果都是"我是loogn，今年22了"*/
String.prototype.format = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        } else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题，谢谢何以笙箫的指出
                    var reg = new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

String.prototype.trim = function () {
    return $.trim(this);
}

String.prototype.startWith = function (str) {
    var reg = new RegExp("^" + str);
    return reg.test(this);
}

String.prototype.endWith = function (str) {
    var reg = new RegExp(str + "$");
    return reg.test(this);
}

var MessageSocket = {
    messageHandlers: {},//信息处理回调
    connect: function (url) {//建立socket连接
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }
        if (window.WebSocket) {
            //ws://localhost:8089/websocket?clientId=1
            var socket = new WebSocket(url);
            socket.onmessage = function (event) {
                var result = eval('(' + event.data + ')');
                if (MessageSocket.messageHandlers[result.category]) {
                    MessageSocket.messageHandlers[result.category](result.message);
                }
            };
            socket.onopen = function (event) {
                //ta.innerHTML = "打开WebSocket服务正常，浏览器支持WebSocket!";
            };
            socket.onclose = function (event) {
                //alert("WebSocket 关闭!");
            };
        } else {
            alert("抱歉，您的浏览器不支持WebSocket协议!");
        }
    },
    registerHandler: function (category, callback) {//注册信息处理回调函数
        this.messageHandlers[category] = callback;
    }
};

$.getUrl = function (url, paramName, paramValue) {
    if (url.indexOf("?") != -1) {
        url += "&" + paramName + "=" + paramValue;
    } else {
        url += "?" + paramName + "=" + paramValue;
    }
    return url;
};

//为Array类添加indexOf方法
function arrayIndexOf() {
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (elt /*, from*/) {
            var len = this.length >>> 0;
            var from = Number(arguments[1]) || 0;
            from = (from < 0) ? Math.ceil(from) : Math.floor(from);
            if (from < 0) {
                from += len;
            }
            for (; from < len; from++) {
                if (from in this && this[from] === elt) {
                    return from;
                }
            }
            return -1;
        };
    }
}

//为Array增加去除重复元素的方法
Array.prototype.removeDuplicate = function () {
    var res = [this[0]];
    for (var i = 1; i < this.length; i++) {
        var repeat = false;
        for (var j = 0; j < res.length; j++) {
            if (this[i] == res[j]) {
                repeat = true;
                break;
            }
        }
        if (!repeat) {
            res.push(this[i]);
        }
    }
    return res;
}

var MapUtils = {
    gcj02_to_bd09: function (gg_lat, gg_lon) {
        var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        var x = gg_lon, y = gg_lat;
        var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        var bd_lon = z * Math.cos(theta) + 0.0065;
        var bd_lat = z * Math.sin(theta) + 0.006;

        var bd_obj = new Object();
        bd_obj.lon = bd_lon;
        bd_obj.lat = bd_lat;

        return bd_obj;
    }
};

var DialogManager = {
    openDialog: function (p) {
        var params = eval("({" + (p || "") + "})");
        params.type = 2;
        params.shadeClose = true;
        params.shade = 0.2;
        params.area = [params.width || '800px', params.height || "500px"];
        params.content = encodeURI(encodeURI(params.url));
        layer.open(params);
    },
    singleSelected: function (p) {
        var id = DataGrid.getSelectId();
        if (id == "" || id == undefined) {
            layer.msg("请选择一行!");
            return false;
        }
        var params = eval("({" + (p || "") + "})");

        var aliasId = params.aid ? params.aid : "id";
        params.url = $.getUrl(params.url, aliasId, id);
        this.openDialog(JSON.stringify(params).replace("{", "").replace("}", ""));
    },
    singleSelected2: function (obj, callBack) {
        var row = DataGrid.getSelectRow();
        if (row == "") {
            $.message("请选中一行数据");
            return;
        }
        var p = obj.attr("p");
        var params = eval("({" + (p || "") + "})");
        var success = callBack(row, params);
        if (!success) {
            return;
        }
        DialogManager.openDialog(JSON.stringify(params).replace("{", "").replace("}", ""));
    }
};

$.ajaxRequest = function (params) {
    $.loading();
    if (params.async != false) {
        params.async = true;
    }
    $.ajax({
        url: params.url,
        data: params.data,
        type: "post",
        dataType: "json",
        async: params.async,
        success: function (data) {
            $.closeLoading();
            params.success(data);
        }
    });
};

//全局loading
var _loading_id;
$.loading = function () {
    if (_loading_id) {
        layer.close(_loading_id);
        _loading_id = false;
    }
    _loading_id = layer.load(1, {shade: [0.1, "#000"]});
};
$.closeLoading = function () {
    //layer.closeAll();
    //alert("aaaa");
    if (_loading_id) {
        layer.close(_loading_id);
        _loading_id = false;
    }
};

$.fn.formSubmit = function (json) {
    var params = json || {parentRefresh: true, parentClose: true};
    params.callBack = params.callBack||function(data){};
    var obj = $(this);
    obj.find("input[type='submit']").prop("disabled", "disabled");
    $.loading();
    obj.ajaxSubmit({
        type: "post",
        url: obj.attr("action"),
        dataType: "json",
        success: function (data) {
            $.closeLoading();
            obj.find("input[type='submit']").removeAttr("disabled");
            if (data.success) {
                var alt = layer.alert("操作成功", function () {
                    obj.resetForm();
                    params.callBack(data);
                    try {
                        if (params.parentClose) {
                            parent.layer.closeAll();
                        }
                        if (params.parentRefresh) {
                            parent.DataGrid.refresh();
                        }
                    } catch (e) {
                        if (params.parentClose) {
                            parent.layer.closeAll();
                        }
                    }
                    layer.close(alt);
                });
                return false;
            }
            layer.msg(data.message);
        }
    });
    return false;
};

$.message = function (message) {
    layer.msg(message);
};

var DataGrid = {
    renderId: '#datagrid',
    noRecord: function (data) {
        /*if (!data.successful) {
         $.message(data.message);
         return;
         }*/
        if (data.rows.length <= 0) {
            //$.message("没有符合条件的数据");
            var body = $(this).data().datagrid.dc.body2;
            var colnum = body.find('table tbody').find("tr:eq(0)").find("td");
            body.find('table tbody').append('<tr><td width="100%" style="line-height:26px;text-align:center;border-left:1px dotted #ccc;" colspan="' + colnum.length + '"><h1>暂无数据</h1></td></tr>');
        }
    },
    onClickRow: function (rowIndex, rowData) {
        DataGrid.getTable().datagrid('clearChecked');
        DataGrid.getTable().datagrid('checkRow', rowIndex);
    },
    getTable: function () {
        return $(this.renderId);
    },
    getCheckedIds: function () {
        var array = new Array();
        var rows = this.getTable().datagrid('getChecked');
        if (rows.length > 0) {
            for (var i = 0; i < rows.length; i++) {
                array.push(rows[i].id);
            }
        }
        return array;
    },
    getCheckedValues: function (field) {
        if (!field) {
            return getCheckedIds();
        }
        var array = new Array();
        var rows = this.getTable().datagrid('getChecked');
        if (rows.length > 0) {
            for (var i = 0; i < rows.length; i++) {
                rows[i][field] && array.push(rows[i][field]);
            }
        }
        return array;
    },
    getCheckedRows: function () {
        return this.getTable().datagrid('getChecked');
    },
    getSelectId: function () {
        var row = this.getTable().datagrid('getSelected');
        return row ? row.id : "";
    },
    getSelectValue: function (field) {
        field = field || 'id';
        var row = this.getTable().datagrid('getSelected');
        return row ? row[field] : "";
    },
    getSelectRow: function () {
        return this.getTable().datagrid('getSelected') || "";
    },
    refresh: function () {
        var table = this.getTable();
        table.datagrid("options").pageNumber = 1;
        table.datagrid({queryParams: this.getParams()});
    },
    reload: function () {
        this.getTable().datagrid('reload');
    },
    options: {},
    defalutOptions: {
        checkOnSelect: true,
        selectOnCheck: false,
        singleSelect: true,
        rownumbers: true,
        method: 'post',
        fitColumns: true,
        pagination: true,
        pageSize: 20
    },
    getParams: function () {
        var queryParams = this.options.params || false;
        if (queryParams) {
            return window[queryParams]();
        }
        return {};
    },
    initParams: function () {
        var table = this.getTable();

        var options_str = table.attr("options") || "";
        if (options_str == "") {
            return;
        }
        var options = eval('({' + options_str + '})');
        for (var key in this.defalutOptions) {
            var value = this.defalutOptions[key];
            options[key] = options[key] || value;
        }
        options.width = options.width || "100%";
        if (!options.height) {
            var windowHeight = $(window).height();
            var operationHeight = $("div.ui-operation").outerHeight();
            var gridHeight = windowHeight - operationHeight - 23;
            options.height = gridHeight + "px";
            $(".ui-table-left div.ui-body").height(gridHeight - 1);
        }

        var str = JSON.stringify(options).replace("{", "").replace("}", "");
        if (!options.onLoadSuccess) {
            str += ',onLoadSuccess:DataGrid.noRecord';
        }else{
        	str += ',onLoadSuccess:' + options.onLoadSuccess;
        }
        if (options.dblClickRow) {
            str += ',onDblClickRow:' + options.dblClickRow;
        }
        if (options.onSelect) {
            str += ',onSelect:' + options.onSelect;
        }
        str += ',onClickRow:DataGrid.onClickRow';
        str += ',striped:true';
        table.removeAttr("options").addClass("easyui-datagrid")
            .attr("data-options", str);
        //$.message(table.attr("data-options"));
        this.options = options;
    },
    init: function () {
        var table = this.getTable() || "";
        if (table == "" || table.length <= 0) {
            return;
        }
        this.initParams();
        table.datagrid({
            //queryParams:this.options.queryParams || {}
        });
    }
};

var FormManager = {
    init: function () {
        $("body").bind("click", function (evt) {
            if ($(evt.target).closest(".ui-more").length == 0) {
                $('.ui-more').hide();
            }
        });
    },
    //json格式：check:false,chkboxType:{"Y":"ps","N":"ps"},id:'hiddenId',name:'showName',url:''
    selectTree: function (obj, paramsStr) {//下拉选择tree，支持单选和多选
        var params = eval("({" + paramsStr + "})");
        var setting = {
            check: {enable: false, chkboxType: {"Y": "", "N": ""}},
            data: {simpleData: {enable: true}},
            callback: {}
        };
        if (params.check === true) {
            setting.check.enable = true;
            if (params.chkboxType) {
                setting.check.chkboxType = params.chkboxType;
            }
        }
        var parent = $(obj).parent();
        var moreDiv = parent.find(".ui-more");
        if (moreDiv.length <= 0) {
            $(obj).after('<div class="ui-more"><ul id="_select_tree" class="ztree"></ul></div>');
        }
        moreDiv = parent.find(".ui-more");
        moreDiv.width(parent.width() - 22);
        if (moreDiv.is(":visible")) {
            moreDiv.toggle();
            return;
        }
        moreDiv.toggle();

        setting.callback.onClick = function (event, treeId, treeNode) {
            if (setting.check.enable) {
                return;
            }
            $(params.id).val(treeNode.id);
            $(params.name).val(treeNode.name);
            moreDiv.hide();
        };
        setting.callback.onCheck = function (event, treeId, treeNode) {
            if (!setting.check.enable) {
                return;
            }
            var zTree = $.fn.zTree.getZTreeObj("_select_tree");
            var checkeds = zTree.getCheckedNodes();
            var ids = new Array(), names = new Array();
            for (var i = 0; i < checkeds.length; i++) {
                ids.push(checkeds[i].id);
                names.push(checkeds[i].name);
            }
            $(params.id).val(ids.join(","));
            $(params.name).val(names.join("，"));
        };

        var treeContent = $("#_select_tree").html() || "";
        if (treeContent == "") {
            $.ajaxRequest({
                url: params.url,
                success: function (data) {
                    $.fn.zTree.init($("#_select_tree"), setting, data.data);
                    showData();
                }
            });
        }

        function showData() {
            //回显数据
            var idsStr = $(params.id).val() || "";
            if (idsStr == "") {
                return;
            }
            var zTree = $.fn.zTree.getZTreeObj("_select_tree");
            var nodes = zTree.transformToArray(zTree.getNodes()); //所有的节点
            if (setting.check.enable) {
                var idArray = idsStr.split(",");
                for (var i = 0; i < nodes.length; i++) {
                    var nodeid = nodes[i].id;
                    for (var j = 0; j < idArray.length; j++) {
                        if (idArray[j] == nodeid) {
                            zTree.checkNode(nodes[i], true, false);
                            break;
                        }
                    }
                }
            } else {
                for (var i = 0; i < nodes.length; i++) {
                    var item = nodes[i];
                    if (item.id != idsStr) {
                        continue;
                    }
                    zTree.expandNode(item, true);
                    zTree.selectNode(item);
                    break;
                }
            }
        }//end showData
    }
};

$(function () {
    arrayIndexOf();
    DataGrid.init();
    FormManager.init();

    $(".open-dialog").click(function () {
        var p = $(this).attr("p");
        DialogManager.openDialog(p);
    });

    $(".singleSelected").click(function () {
        var p = $(this).attr("p");
        DialogManager.singleSelected(p);
    });

    $(".ajax-form").unbind().submit(function () {
        var form = $(this);
        form.formSubmit();
        return false;
    });

    $(".search-button").click(function () {
        DataGrid.refresh();
    });

    $(".select-tree").click(function (e) {
        FormManager.selectTree(this, $(this).attr("p"));
        stopPropagation(e);
    });
});